//
//  MineBrowseRecordsViewController.m
//  copyrightTrading
//
//  Created by 郭子一 on 2020/10/8.
//  Copyright © 2020 郭子一. All rights reserved.
//

#import "MineBrowseRecordsViewController.h"
#import "VIPVideoPictureCell.h"
@interface MineBrowseRecordsViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *stateCollectionView; // 模式列表
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) NSMutableArray *dataArray; // 模式列表
@property (nonatomic, assign) BOOL isEdit;
@property (nonatomic, strong) NSMutableArray *selectIDArray; //选中要删除的列表
@property (nonatomic, strong) NSMutableArray *allIDArray; // 全部的id数组，用来跟选中的id做比较的
@property (nonatomic, strong) UIView *bottomView; // 
@property (nonatomic, strong) UIButton *selectAllBtn;
@property (nonatomic, strong) UIButton *deleteBtn; // 结算/删除按钮
@end

@implementation MineBrowseRecordsViewController

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)selectIDArray
{
    if (!_selectIDArray) {
        _selectIDArray = [NSMutableArray array];
    }
    return _selectIDArray;
}

- (NSMutableArray *)allIDArray
{
    if (!_allIDArray) {
        _allIDArray = [NSMutableArray array];
    }
    return _allIDArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.pageIndex = 0;
}

- (void)setupUI
{
    UIView *headerView = [UIView new];
    headerView.backgroundColor = RGB_VALUE(0xDC0000);
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.mas_equalTo(Height_NavBar);
    }];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"whiteBack"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setHitEdgeInsets:UIEdgeInsetsMake(-15, -15, -15, -15)];
    [headerView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-14);
        make.left.offset(18);
        make.width.height.mas_equalTo(16);
    }];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = @"浏览记录";
    titleLabel.font = JSS_MEDIUM_FONT(17);
    titleLabel.textColor = RGB_VALUE(0xFFFFFF);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-9);
        make.centerX.offset(0);
        make.width.mas_equalTo(135);
        make.height.mas_equalTo(24);
    }];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [loginBtn setTitle:@"完成" forState:UIControlStateSelected];
    [loginBtn setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateNormal];
    [loginBtn.titleLabel setFont:JSS_MEDIUM_FONT_7];
    [loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [loginBtn setHitEdgeInsets:UIEdgeInsetsMake(-15, -15, -9, 0)];
    [headerView addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(titleLabel);
        make.width.mas_equalTo(72);
        make.right.offset(-2);
        make.height.mas_equalTo(22);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(20, 16, 20, 16);
    layout.minimumLineSpacing = 7;
    layout.minimumInteritemSpacing = 6;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.stateCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.stateCollectionView.delegate = self;
    self.stateCollectionView.dataSource = self;
    self.stateCollectionView.backgroundColor = UIColor.clearColor;
    self.stateCollectionView.showsHorizontalScrollIndicator = NO;
    [self.stateCollectionView registerClass:[VIPVideoPictureCell class] forCellWithReuseIdentifier:@"VIPVideoPictureCell"];
    [self.view addSubview:self.stateCollectionView];
    [self.stateCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.top.equalTo(headerView.mas_bottom);
    }];
    
    @weakify(self)
    self.stateCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        self.pageIndex = 0;
        [self requestData];
    }];
    self.stateCollectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        self.pageIndex ++;
        [self requestData];
    }];
    
//    self.stateCollectionView.mj_footer.ignoredScrollViewContentInsetBottom = TabbarSafeBottomMargin;
    [self requestData];
    
    self.bottomView = [UIView new];
    self.bottomView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.bottom.offset(0);
        make.height.mas_equalTo(Height_TabBar);
    }];
    
    self.selectAllBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.selectAllBtn setTitle:@"全选" forState:UIControlStateNormal];
    [self.selectAllBtn setTitleColor:RGB_VALUE(0x989898) forState:UIControlStateNormal];
    [self.selectAllBtn setImage:[UIImage imageNamed:@"MineCartCircle"] forState:UIControlStateNormal];
    [self.selectAllBtn setImage:[UIImage imageNamed:@"MineCartSelect"] forState:UIControlStateSelected];
    [self.selectAllBtn.titleLabel setFont:JSS_MEDIUM_FONT_4];
    [self.selectAllBtn addTarget:self action:@selector(selectAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.selectAllBtn layoutButtonWithEdgeInsetsStyle:DVButtonEdgeInsetsStyleLeft imageTitleSpace:8];
    [self.bottomView addSubview:self.selectAllBtn];
    [self.selectAllBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(13);
        make.left.offset(27);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(24);
    }];
    
    self.deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    [self.deleteBtn setTitleColor:RGB_VALUE(0x000000) forState:UIControlStateNormal];
    [self.deleteBtn.titleLabel setFont:JSS_MEDIUM_FONT_4];
    [self.deleteBtn addTarget:self action:@selector(deleteBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.deleteBtn setHitEdgeInsets:UIEdgeInsetsMake(-15, -15, -15, -15)];
    [self.bottomView addSubview:self.deleteBtn];
    [self.deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.selectAllBtn);
        make.right.offset(-34);
        make.width.mas_equalTo(28);
        make.height.mas_equalTo(20);
    }];
    self.bottomView.hidden = YES;
    
}

// 全选
- (void)selectAllBtnClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {

        for (NSDictionary *dic in self.dataArray) {
            [self.selectIDArray addObject:dic[@"id"]];
        }
        [self.stateCollectionView reloadData];
        
    } else {
        [self.selectIDArray removeAllObjects];
        [self.stateCollectionView reloadData];
    }
}

// 删除按钮
- (void)deleteBtnClick
{
    self.selectAllBtn.selected = NO;
    self.pageIndex = 0;
    NSDictionary *paramDic = @{
        @"id":self.selectIDArray
    };
    [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypePost URLString:@"delview" parameters:paramDic done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        [self requestData];
        
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

- (void)requestData
{
    NSDictionary *paramDic = @{
        @"page":@(self.pageIndex),
        @"limit":@(10)
    };
    [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypeGet URLString:@"userview" parameters:paramDic done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if (self.pageIndex == 0) {
            [self.dataArray removeAllObjects];
            [self.dataArray addObjectsFromArray:responseObject[@"data"][@"list"][@"list"]];
        } else {
            [self.dataArray addObjectsFromArray:responseObject[@"data"][@"list"][@"list"]];
        }
        [self.allIDArray removeAllObjects];
        for (NSDictionary *dic in self.dataArray) {
            [self.allIDArray addObject:dic[@"id"]];
        }
        [self.stateCollectionView.mj_header endRefreshing];
        if (self.pageIndex == [responseObject[@"data"][@"list"][@"page_sum"] integerValue]) {
            [self.stateCollectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.stateCollectionView.mj_footer endRefreshing];
        }
        [self.stateCollectionView reloadData];
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [self.stateCollectionView.mj_header endRefreshing];
        [self.stateCollectionView.mj_footer endRefreshing];
    }];
}

- (void)backBtnClick
{
    [self pop];
}

// 编辑点击事件
- (void)loginBtnClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    self.isEdit = sender.selected;
    self.bottomView.hidden = !sender.selected;
    self.selectAllBtn.selected = !sender.selected;
    if (!sender.selected) {
//        self.pageIndex = 0;
//        NSDictionary *paramDic = @{
//            @"id":self.selectIDArray[0]
//        };
//        [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypePost URLString:@"delview" parameters:paramDic done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//
//            [self requestData];
//
//        } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
//
//        }];
        [self.selectIDArray removeAllObjects];
        [self.stateCollectionView reloadData];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kDeviceWidth - 32 - 7)/2, 108);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    VIPVideoPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VIPVideoPictureCell" forIndexPath:indexPath];
    NSDictionary *dataDic = self.dataArray[indexPath.row];
    cell.dataDic = dataDic;
    cell.isSelcted = [self.selectIDArray containsObject:dataDic[@"id"]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dataDic = self.dataArray[indexPath.row];
    if (self.isEdit) {
        if ([self.selectIDArray containsObject:dataDic[@"id"]]) {
            [self.selectIDArray removeObject:dataDic[@"id"]];
        } else {
            [self.selectIDArray addObject:dataDic[@"id"]];
        }
        if ([self array:self.selectIDArray isEqualTo:self.allIDArray]) {
            self.selectAllBtn.selected = YES;
        } else {
            self.selectAllBtn.selected = NO;
        }
        [self.stateCollectionView reloadData];
        
    } else {
        [self pushVideoDetailVCWithID:dataDic[@"id"]];
    }
}

- (BOOL)array:(NSMutableArray *)array1 isEqualTo:(NSMutableArray *)array2 {
    if (array1.count != array2.count) {
        return NO;
    }
    for (NSIndexPath *str in array1) {
        if (![array2 containsObject:str]) {
            return NO;
        }
    }
    for (NSIndexPath *str in array2) {
        if (![array1 containsObject:str]) {
            return NO;
        }
    }
    return YES;
}
@end
